import React, { PureComponent } from 'react';
import { Form, Input, Upload, TreeSelect, notification } from 'antd';
import { connect } from 'dva';
import { worker } from "../../utils/worker"
import "./form.less"
import moment from "moment"
const { TextArea } = Input;
class CrossSectionBase extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            validateRes1: null,
            validateRes2: null,
            fileList: [],
            data: {},
            loading: false,
            expandedKeys: [],
            expandedKeys2: [],
            checkedKeys: [],
            sort: [{ id: '6', name: '盖梁' }, { id: '7', name: '方柱墩身' }, { id: '12', name: "圆柱墩身" }, { id: '11', name: "基础" }],
        }
        this.onConfirm = this.onConfirm.bind(this);
        this.onOk = this.onOk.bind(this)
        this.onSelect = this.onSelect.bind(this)
        this.getFormValues = this.getFormValues.bind(this)
        this.updateFormData = this.updateFormData.bind(this)
        this.validate1 = this.validate1.bind(this)
        this.validate2 = this.validate2.bind(this)
        this.onChange1 = this.onChange1.bind(this)
        this.onChange2 = this.onChange2.bind(this)
        this.onCheck = this.onCheck.bind(this)
        this.validate = this.validate.bind(this)
        this.warn = this.warn.bind(this)
    }
    isContained(aa, bb) {
        if (!(aa instanceof Array) || !(bb instanceof Array) || ((aa.length < bb.length))) { return false; }
        var aaStr = aa.toString();
        const len = bb.length
        for (var i = 0; i < len; i++) { if (aaStr.indexOf(bb[i]) < 0) return false; }
        return true;

    }
     getFormValues(check) {
        return new Promise(async(resolve, reject) => {
            const {setFieldsValue}=this.props.form
            const {fileList}=this.state;
            if(fileList&&fileList.length){
                await setFieldsValue({
                    file:fileList[0].originFileObj?fileList[0].originFileObj:"1"
                })
            }else{
                await setFieldsValue({
                    file:null
                })
            }
            if (!check) {
                this.props.form.validateFields((error, values) => {
                    if (!error) {
                        values.file=fileList[0].originFileObj
                        resolve(values)
                    } else {
                        reject(error)
                    }
                    
                })
            } else {
    
                let values = this.props.form.getFieldsValue()
                values.file=fileList[0].originFileObj
                resolve(values)
            }
            

        })
    }
    onChange1(e) {
        this.setState({
            validateRes1: this.validate1(e)
        })
    }
    onChange2(e) {
        this.setState({
            validateRes2: this.validate2(e)
        })
    }
    warn(message) {
        this.st2 = setTimeout(() => {
            clearTimeout(this.st2)
            notification.warn({ message })
        }, 10)
    }
    validate(e) {
        if (this.st2) {
            clearTimeout(this.st2)
        }
        return new Promise((resolve, reject) => {
            let { fileList } = this.state;
            if (e.file.originFileObj.webkitRelativePath.split('/').length > 2) {
                this.warn("此操作上传的文件夹中含有其他文件夹，请移除内部文件夹!")
                reject()
                return;
            }
            if (new RegExp(/\.php|\.exe|\.cmd|\.bat|\.java/).test(e.file.originFileObj.webkitRelativePath)) {
                this.warn("文件非法!")
                reject()
                return;
            }
            fileList.push(e.file)
            this.setState({
                fileList: fileList
            })
            resolve()
        })
    }
    async componentDidMount() {
        if (this.props.onLoaded) {
            this.props.onLoaded(this);
        }

        const { dictlist, extra,detail } = this.props;
        let res = await this.props.crossTree()
        let resc = await worker.loopTreeNode(res, null, true, true)
        if (resc) {
            this.setState({
                expandedKeys: resc.map(item => item.key),
                treeData: resc
            })
        }
        this.setState({
            isShowList: dictlist.filter(item => item.dictType == "is_show"),
            isEffectiveList: dictlist.filter(item => item.dictType == "is_effective"),
            definitionFileCategory: dictlist.filter(item => item.dictType == "definition_file_category"),
            dynamicBlock: dictlist.filter(item => item.dictType == "dynamic_block"),
        })

    }

    onConfirm(params = {}) {
        this.props.form.validateFields((error, values) => {
        
            if (!error) {
                
                const {fileList}=this.state;
                this.props.form.resetFields()
                values.file=fileList[0]
                
                this.props.refStructure(values, (structure) => {
                    if (params.onSuccess) {
                        params.onSuccess(structure);
                    }
                }, (error) => {
                    if (params.onError) {
                        params.onError(error);
                    }
                });
            } else {
                if (params.onError) {
                    params.onError(error);
                }
            }
        });
    }
    onSelect(e) {
        const { setFieldsValue } = this.props.form;
        setFieldsValue({
            definitionIds: e
        })
    }
    updateFormData(values) {
        const { data } = this.state;
        values.createTime = moment(values.createTime)
        if (values.crossSectionCategoryId) {
            Object.assign(data, values)
            if (values.uploadFileInfo) {
                this.setState({
                    fileList:[values.uploadFileInfo]
                })
            }
            this.setState({
                data
            })
        }

    }
    onOk(e) {
        console.log(e)
    }
    validate1(value) {
        return value - 0 < 0 || value - 1 > 0 ? {
            validateStatus: 'error',
            errorMsg: "数值0-1之间",
        } : {
                validateStatus: 'success',
                errorMsg: null,
            }

    }
    validate2(value) {
        return value - 0 < 0 || value - 3 > 0 ? {
            validateStatus: 'error',
            errorMsg: "数值0-3之间",
        } : {
                validateStatus: 'success',
                errorMsg: null,
            }

    }
    onCheck(e, a) {
        this.setState({
            checkedKeys: e
        })

    }
    componentWillUnmount() {
        if (this.st) {
            clearTimeout(this.st)
        }
        if (this.st2) {
            clearTimeout(this.st2)
        }
    }
    render() {
        const {
            form = {},
            mode
        } = this.props;
        const { getFieldDecorator, setFieldsValue } = form;
        const { data, fileList, treeData,  } = this.state;
        return (
            <Form
                className="strBForm"
                style={{ maxWidth: "1200px", margin: 'auto', border: '1px solid #ececec', padding: '30px 0 0 0', display: 'flex', flexWrap: 'wrap', justifyContent: 'space-evenly' }}
                labelCol={{ span: 7 }}
                wrapperCol={{ span: 17 }}
            ><Form.Item labelCol={{ span: 4 }}
                wrapperCol={{ span: 20 }} style={{ width: "90%" }} label='截面库'>
                    {getFieldDecorator('file', {
                        rules: [
                            { required: true, message: '截面库图片' }
                        ],
                        initialValue: data ? [data.uploadFileInfo] : []
                    })(
                        <Upload
                            accept="image/jpg,image/png,image/webp"
                            multiple
                            listType='picture'
                            disabled={mode == 'overview'}
                            progress={
                                {
                                    strokeColor: {
                                        '0%': '#108ee9',
                                        '100%': '#87d068',
                                    },
                                    strokeWidth: 3,
                                    format: percent => `${parseFloat(percent.toFixed(2))}%`,
                                }
                            }
                            customRequest={(e) => {

                            }}
                            fileList={fileList}
                            beforeUpload={async e => {
                                if (fileList && fileList.length) {
                                    await this.setState({
                                        fileList: []
                                    })

                                }
                            }}
                            onRemove={file => {
                                const index = this.state.fileList.indexOf(file);
                                this.state.fileList.splice(index, 1);
                                this.setState({
                                    fileList: [...this.state.fileList]
                                })
                                setFieldsValue({
                                    file:null
                                })
                            }}
                            onChange={(e) => {
                                if (this.st) {
                                    clearTimeout(this.st)
                                }
                                if (this.st2) {
                                    clearTimeout(this.st2)
                                }
                                this.validate(e)
                                if (e.file.originFileObj) {
                                    e.file.status = "done"
                                    this.setState({
                                        fileupdated:true,
                                        directary: e.file.originFileObj.webkitRelativePath.split('/')[0]
                                    })
                                }

                            }}
                        >
                            <div className="upload" style={{ width: '120px', height: '120px', borderRadius: '0.2em', lineHeight: '120px', color: '#888', border: 'dashed 0.5px #d8d8d8', cursor: 'pointer', textAlign: 'center', overflow: 'hidden', marginRight: "10px" }}>
                                <span>上传文件</span>
                            </div>
                        </Upload>
                    )}
                </Form.Item>


                <Form.Item className="half"
                    label='截面库名称'>
                    {getFieldDecorator('name', {
                        rules: [
                            { required: true, message: '截面库名称' }
                        ],
                        initialValue: data ? data.name : undefined
                    })(
                        <Input />
                    )}
                </Form.Item>
                <Form.Item className="half" label='截面库类别'>
                    {getFieldDecorator('crossSectionCategoryId', {
                        rules: [
                            { required: true, message: '截面库类别' }
                        ],
                        initialValue: data && data.crossSectionCategoryId ? data.crossSectionCategoryId : undefined
                    })(
                        <TreeSelect
                            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                            placeholder="请选择截面库"
                            treeData={treeData}
                            treeDefaultExpandAll
                        ></TreeSelect>
                    )}
                </Form.Item>


                <Form.Item className="half" label='描述'>
                    {getFieldDecorator('description', {
                        rules: [
                            { required: true, message: '描述' }
                        ],
                        initialValue: data && data.description ? data.description : undefined
                    })(
                        <TextArea rows={6}></TextArea>
                    )}
                </Form.Item>

                <div className="half">

                </div>
                <div className="half">

                </div>
                {
                    mode != 'add' ? <Form.Item className="hide"
                        label='ID'>
                        {getFieldDecorator('id', {
                            rules: [
                                { required: true, message: '必填' }
                            ],
                            initialValue: data ? data.id : undefined
                        })(
                            <Input />
                        )}
                    </Form.Item> : undefined
                }
            </Form>
        );
    }
}

export default connect(
    ({
        dict: { dictlist }
    }) => {
        return { dictlist };
    },
    dispatch => ({
        crossTree: (values) => dispatch({
            type: 'renforce/crossTree',
            payload: values
        }),
    })
)(Form.create('CrossSectionBase', {

})(CrossSectionBase));